<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button class="setBtn">新增</button>
    <button class="getBtn">获取</button>
</body>
<script>

    // cookie的特征
    // 1. cookie的存取都依赖于document.cookie(字符串)
    // 2. cookie也是以键值对的形式存在的(一条)
    // 3. cookie存储时是一条一条存储的,获取时是将所有的cookie整合到一整个字符串中,用"; "分隔
    // 3. cookie可以设置存储路径 和 过期时间(默认:浏览器关闭过期)

    var setBtn = document.getElementsByClassName("setBtn")[0];
    var getBtn = document.getElementsByClassName("getBtn")[0];

    setBtn.onclick = function () {
        // var date = new Date();
        // date.setDate(date.getDate() + 31);

        // document.cookie = "user=a123123;expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "pwd=123123;expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "phone=17386141517;expires=" + date.toUTCString() + ";path=/";
        // document.cookie = "email=123123@qq.com;expires=" + date.toUTCString() + ";path=/";


        setCookie("user", "a123123", 31 * 24 * 60 * 60);
        setCookie("pwd", "123123");
        setCookie("phone", "17386141517", 7 * 24 * 60 * 60);
        setCookie("email", "123123@qq.com", 24 * 60 * 60);
    }


    getBtn.onclick = function () {
        console.log(getCookie("user"));
        console.log(getCookie("pwd"));
        console.log(getCookie("phone"));
        console.log(getCookie("email"));
        console.log(getCookie("height"));
    }


    function setCookie(key, value, expires, path = "/") {
        if (expires) {
            var date = new Date();
            date.setSeconds(date.getSeconds() + expires);
            document.cookie = key + "=" + value + ";expires=" + date.toUTCString() + ";path=" + path;
        } else {
            document.cookie = key + "=" + value + ";path=" + path;
        }
    }


    function getCookie(key) {
        var cookie = document.cookie;
        if (cookie) {
            var list = cookie.split("; ");
            for (var i = 0; i < list.length; i++) {
                var item = list[i];  // 每一条数据 'user=a123123'
                var name = item.split("=")[0]; // "user"
                var val = item.split("=")[1]; // "a123123"

                if (key == name) {
                    return val;
                }
            }
        }
        return "";
    }
</script>

</html>